package abmb.pages;


import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import abmb.utils.PageLinks;
import abmb.utils.PageParts;
import abmb.utils.Utilities;

/**
 * Servlet implementation class Login
 * @author Andrea Balboni
 * @version 1.0
 */
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Login() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		PageParts pp=new abmb.utils.PageParts();
		Utilities utils=new abmb.utils.Utilities();
		HttpSession session=request.getSession(true);
		response.setContentType("text/html");
		PrintWriter p= response.getWriter();
		p.println(pp.printHTMLHeader("AB-Microblog Login",utils.isLoggedIn(session)));
		p.println("<div class=\"c1\"><section>");

		p.println("<h1>Login</h1>");
		p.println("<form id=\"login\" action=\""+PageLinks.getLoginLink()+"\" method=\"POST\">");
		p.println("<fieldset>");
		p.println("<legend>Enter your credentials</legend>");
		p.println("<label>Username: <input type=\"text\" id=\"nickname\" name=\"nickname\" placeholder=\"nickname\" required autofocus autocomplete=\"on\"></label>");
		p.println("<label>Password: <input type=\"password\" id=\"passwd\" name=\"passwd\" placeholder=\"password\" required></label>");
		p.println("</fieldset>");
		p.println("<fieldset>");
		p.println("<input type=\"submit\" value=\"Login\">");
		p.println("<input type=\"reset\" value=\"Reset\">");
		p.println("</fieldset>");
		p.println("</form>");
		p.println("</section></div>");

		
		/*Controllo le credenziali inserite ed eseguo il login*/
		if(request.getParameter("nickname")!=null && request.getParameter("passwd")!=null){
			String username=(String)request.getParameter("nickname");
			String password=(String)request.getParameter("passwd");
			if(utils.checkUserRegistration(username)){
				if(utils.doLogin(username, password, session, p)){
					response.sendRedirect(response.encodeRedirectURL(PageLinks.getIndexLink()));
				}
			}
		}
		p.println(pp.printFooterSection());
		p.println(pp.printHTMLFooter());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}
